import React, { Component } from 'react';
import { inject, observer } from 'mobx-react';
import { Spin, Button, message } from 'antd';
import {
  WeaDialog,
  WeaErrorPage,
  WeaTools,
  WeaLocaleProvider,
  WeaSearchGroup,
  WeaFormItem,
  WeaDatePicker,
  WeaCheckbox,
} from 'ecCom';
import { RenderForm } from '../emailSetting/util';
import * as EmailUtil from '../../util/EmailUtil';

const getLabel = WeaLocaleProvider.getLabel;
const { tryCatch } = WeaTools;

const store = ['routing', 'emailMainStore', 'todoNewStore', 'emailMenuStore'];

@tryCatch(
  React,
  props => (
    <WeaErrorPage
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_WeaErrorPage@1cvr8b`}
      msg={
        props.error ||
        getLabel(186, '对不起，该页面异常，请联系管理员！', 'error')
      }
    />
  ),
  { error: '' },
)
@inject(...store)
@observer
class Todo extends Component {
  static displayName = 'Todo';
  constructor(props) {
    super(props);
    this.isInstanceMounted = false;
    this.prefixClass = 'email-todo';
  }

  componentDidMount() {
    this.isInstanceMounted = true;
  }

  componentWillUnmount() {
    this.isInstanceMounted = false;
  }

  formatDate = (time, str) => {
    let obj = {
      yyyy: time.getFullYear(),
      MM: `0${time.getMonth() + 1}`.slice(-2),
      dd: `0${time.getDate()}`.slice(-2),
      HH: `0${time.getHours()}`.slice(-2),
      mm: `0${time.getMinutes()}`.slice(-2),
    };
    return str.replace(/([a-z]+)/gi, v => obj[v]);
  };

  range = (start, end) => {
    const result = [];
    for (let i = start; i < end; i++) {
      result.push(i);
    }
    return result;
  };

  onDataPickerChange = (v) => {
    const {
      todoNewStore: { todoForm, setStoreState },
    } = this.props;
    setStoreState({ dealTime: v });
    todoForm.updateFields({ waitdealtime: { value: v } });
  };
  onRemindChange = (v) => {
    const {
      todoNewStore: { todoForm, setStoreState },
    } = this.props;
    setStoreState({ remindTime: v });
    todoForm.updateFields({ wdremindtime: { value: v } });
  };

  getForm = (remind, remark, form, fields) => {
    const {
      todoNewStore: { remindTime, dealTime },
    } = this.props;
    const { isFormInit } = form;
    const { waitdealtime, wdremindtime } = form.getFormParams();
    let nowTime = this.formatDate(new Date(), 'yyyy-MM-dd HH:mm');
    let dayTime = new Date().getDate();
    let hourTime = new Date().getHours();
    let secondTime = new Date().getMinutes();
    let group = [];
    isFormInit &&
      fields &&
      fields.map((c) => {
        if (c.key === 'time') {
          let items = [];
          c.items.map((field) => {
            items.push({
              com: (
                <WeaFormItem
                  ecId={`${
                    (this && this.props && this.props.ecId) || ''
                  }_WeaFormItem@zvo1i8@${field.domkey[0]}`}
                  label={`${field.label}`}
                  labelCol={{ span: `${field.labelcol}` }}
                  wrapperCol={{ span: `${field.fieldcol}` }}
                  className={`email-form-formItem ${field.domkey[0]}`}
                  error={form.getError(field)}
                  tipPosition="bottom"
                >
                  <WeaDatePicker
                    ecId={`${
                      (this && this.props && this.props.ecId) || ''
                    }_WeaDatePicker@s3ov4d@${field.domkey[0]}`}
                    value={dealTime || field.value}
                    viewAttr={3}
                    startValue={wdremindtime}
                    onChange={this.onDataPickerChange}
                  />
                </WeaFormItem>
              ),
            });
          });
          group.push(
            <WeaSearchGroup
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaSearchGroup@txjzks@searchgroup`}
              col={1}
              title={c.title}
              needTigger={false}
              showGroup={c.defaultshow}
              items={items}
            />,
          );
        } else if (c.key === 'remind' && remind * 1) {
          let items = [];
          c.items.map((field) => {
            if (field.domkey[0] === 'waitdealway') {
              items.push({ com: RenderForm(form, field) });
            } else {
              items.push({
                com: (
                  <WeaFormItem
                    ecId={`${
                      (this && this.props && this.props.ecId) || ''
                    }_WeaFormItem@zsu57u@${field.domkey[0]}`}
                    label={`${field.label}`}
                    labelCol={{ span: `${field.labelcol}` }}
                    wrapperCol={{ span: `${field.fieldcol}` }}
                    className={`email-form-formItem ${field.domkey[0]}`}
                    error={form.getError(field)}
                    tipPosition="bottom"
                  >
                    <WeaDatePicker
                      ecId={`${
                        (this && this.props && this.props.ecId) || ''
                      }_WeaDatePicker@umeuvw@${field.domkey[0]}`}
                      value={remindTime || ''}
                      showTime={{ format: 'HH:mm:ss' }}
                      format="yyyy-MM-dd HH:mm:ss"
                      // format="yyyy-MM-dd HH:mm"
                      viewAttr={3}
                      startValue={nowTime}
                      endValue={waitdealtime || ''}
                      onChange={this.onRemindChange}
                      needSecond
                      disabledTimeConfig={{
                        dayConfig: {
                          [dayTime]: {
                            disabledHour: this.range(0, hourTime),
                            HourConfig: {
                              [hourTime]: {
                                disabledMinute: this.range(0, secondTime),
                                minuteConfig: {
                                  [secondTime]: [11],
                                },
                              },
                            },
                          },
                        },
                      }}
                    />
                  </WeaFormItem>
                ),
              });
            }
          });
          group.push(
            <WeaSearchGroup
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaSearchGroup@cxmtj2@${c.title}`}
              col={1}
              title={c.title}
              needTigger={false}
              showGroup={c.defaultshow}
              items={items}
            />,
          );
        } else if (c.key === 'remark' && remark * 1) {
          let items = [];
          c.items.map((field) => {
            items.push({ com: RenderForm(form, field) });
          });
          group.push(
            <WeaSearchGroup
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaSearchGroup@6sjb5x@${c.title}`}
              col={1}
              title={c.title}
              needTigger={false}
              showGroup={c.defaultshow}
              items={items}
            />,
          );
        }
      });
    return group;
  };

  todoSubmit = () => {
    const {
      emailMainStore: { todoSetIds },
      todoNewStore,
      emailMenuStore,
    } = this.props;
    const { todoForm, saveTodo, remind, remark } = todoNewStore;
    let formParams = todoForm.getFormParams();
    let params = {
      ...formParams,
      op_hasNote: remark,
      op_hasRemind: remind,
      mailIds: todoSetIds,
    };
    let remindValidate =
      remind * 1 &&
      (formParams.waitdealway === '' || formParams.wdremindtime === '');
    let remarkValidate = remark * 1 && formParams.waitdealnote.trim() === '';
    if (formParams.waitdealtime === '' || remindValidate || remarkValidate) {
      message.warning(getLabel(384331, '您有必填项没有填写，不能保存！'));
      return;
    }
    saveTodo(params).then(async (res) => {
      if (res.status === '1') {
        const { hasMenu, getMenu } = emailMenuStore;
        this.cancel();
        this.props.refesh(res, todoSetIds);
        // 标准模式下刷新待办邮箱 数字
        if (!hasMenu) {
          let utilRes = await EmailUtil.updateMenuCount({}, 'waitdeal');
          if (!utilRes) {
            getMenu();
          }
        }
      }
    });
  };

  cancel = () => {
    const {
      emailMainStore: { setState },
      todoNewStore: { clear, todoForm },
    } = this.props;
    setState({ todoSetVisible: '', todoSetIds: [] });
    todoForm.resetForm();
    clear();
  };

  remarkChange = (v) => {
    const { todoNewStore } = this.props;
    const { setStoreState, todoForm } = todoNewStore;
    setStoreState({ remark: v });
    if (v * 1 === 0) {
      todoForm.updateFields({ waitdealnote: { value: '' } });
    }
  };

  remindChange = (v) => {
    const { todoNewStore } = this.props;
    const { setStoreState, todoForm } = todoNewStore;
    setStoreState({ remind: v });
    if (v * 1 === 0) {
      setStoreState({ remindTime: '' });
      todoForm.updateFields({
        wdremindtime: { value: '' },
        waitdealway: { value: '' },
      });
    } else {
      todoForm.updateFields({ waitdealway: { value: '5' } });
    }
  };

  render() {
    const {
      emailMainStore: { todoSetVisible },
      todoNewStore,
    } = this.props;
    const { loading, remind, remark, todoForm, todoFields } = todoNewStore;
    const buttons = [
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@34xrg7@onsave`}
        type="primary"
        onClick={this.todoSubmit}
      >
        {getLabel(30986, '保存')}
      </Button>,
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@ajs1bb@oncancel`}
        onClick={this.cancel}
      >
        {getLabel(201, '取消')}
      </Button>,
    ];
    const bottomLeftBtn = [
      <WeaCheckbox
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaCheckbox@eln9sm@addremind`}
        content={getLabel(83135, '添加提醒')}
        value={remind}
        onChange={this.remindChange}
      />,
      <WeaCheckbox
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaCheckbox@gedgu3@addremark`}
        content={getLabel(83136, '添加备注')}
        value={remark}
        onChange={this.remarkChange}
      />,
    ];
    return (
      <WeaDialog
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaDialog@tels4w`}
        className={`${this.prefixClass}-dialog`}
        icon="icon-coms-email"
        iconBgcolor="#a0b0ba"
        title={getLabel(507597, '待办邮件设置')}
        visible={todoSetVisible}
        style={{ width: 580, maxHeight: 530 }}
        buttons={buttons}
        bottomLeft={bottomLeftBtn}
        onCancel={this.cancel}
        hasScroll
      >
        <Spin
          ecId={`${(this && this.props && this.props.ecId) || ''}_Spin@qvsrhg`}
          spinning={loading}
        >
          {this.getForm(remind, remark, todoForm, todoFields)}
        </Spin>
      </WeaDialog>
    );
  }
}

export default Todo;
